package com.lu.statistics.entity.send;


import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.google.gson.Gson;
import com.lu.statistics.loader.DataLoader;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class SendSmsUtils {
    private final String  ACCESS_KEY_ID = DataLoader.getConfigValue("ACCESS_KEY_ID");
    private final String ACCESS_KEY_SECRET = DataLoader.getConfigValue("ACCESS_KEY_SECRET");
    public Integer sendSms(String phone) throws ExecutionException, InterruptedException {
        String signSmsName = DataLoader.getConfigValue("SIGN_SMS_NAME");
        String signSmsTemplate = DataLoader.getConfigValue("SIGN_SMS_TEMPLATE");

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(ACCESS_KEY_ID)
                .accessKeySecret(ACCESS_KEY_SECRET)
                .build());

        AsyncClient client = AsyncClient.builder()
                .region("cn-hangzhou")
                .credentialsProvider(provider)
                .overrideConfiguration(ClientOverrideConfiguration.create()
                        .setEndpointOverride("dysmsapi.aliyuncs.com")).build();

        int random = (int) (Math.random() * 9000) + 1000;
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(signSmsName)
                .templateCode(signSmsTemplate)
                .phoneNumbers(phone)
                .templateParam(String.format("{\"code\":\"%s\"}", random))
                .build();

        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        SendSmsResponse resp = response.get();
        System.out.println("+++++++" + new Gson().toJson(resp) + "+++++++");
        client.close();
        return random;
    }

}
